import React from 'react';
import { Icon, Modal, Alert, Spin, Popover, Table } from 'antd';
import { messages } from 'share/common';
import Condition from 'components/condition';
import expenseReportService from '../../expense-report/expense-report.service';

const { If } = Condition;

class ApplicationApportion extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      loading: false,
      buttonLoading: false,
      applicationApportion: [],
    };
  }

  handleCancel = () => {
    this.setState({ visible: false });
  };

  handleOk = (selectedKeys) => {
    let { defaultExpenseApportion, expenseApportion, handleApplicationChange } = this.props;
    const { applicationApportion } = this.state;
    selectedKeys.forEach(id => {
      applicationApportion.some(item => {
        if (item.id === id) {
          let defaultExpense = JSON.parse(JSON.stringify(defaultExpenseApportion));
          defaultExpense.amount = 0;
          defaultExpense.proportion = 0;
          defaultExpense.defaultApportion = false;
          defaultExpense.costCenterItems = item.costCenterItemsForAdd;
          defaultExpense.apportionmentOID = null;
          defaultExpense.apportionmentLabels = [];
          defaultExpense.applicationApportionmentId = item.applicationApportionmentId;
          defaultExpense.applicationApportionmentIds = item.applicationApportionmentIds;
          expenseApportion.push(defaultExpense);
          return true;
        }
      });
    });

    this.setState({ visible: false });
    handleApplicationChange(expenseApportion);
  };

  handleLoadingApplicationInvoice = () => {
    const { applicationApportionmentIds } = this.props;
    let { applicationApportion } = this.state;
    const server = () => {
      expenseReportService
        .getApplicationApportion({ applicationApportionmentIds: applicationApportionmentIds.join(',') })
        .then((res) => {
          applicationApportion = [res.data];
        })
        .catch(e => {
          errorMessage(e.response);
        })
        .finally(() => {
          this.setState(
            { applicationApportion, loading: false },
            () => { this.setState({ visible: true });});
        });
    };

    this.setState({ loading: true }, server);
  };

  handleShow = () => {
    let { applicationApportion } = this.state;
    const { expenseReportOID, currencyCode, expenseTypeId, invoiceOID } = this.props;
    const server = () => {
      expenseReportService
        .getApplicationApportions({ expenseReportOID, expenseTypeId, currency: currencyCode, invoiceOID })
        .then(res => {
          applicationApportion = res.data;
          applicationApportion.map((item, index) => {item.id = item.businessCodes.join('-') + index;return item});
        })
        .finally(() => {
          this.setState({ applicationApportion, buttonLoading: false, visible: true });
        });
    };

    this.setState({ buttonLoading: true }, server);
  };

  WraooedModal = (WraooedComponent) => {
    const { flag } = this.props, { applicationApportion } = this.state;
    return class extends WraooedComponent {
      constructor(props) {
        super(props);
        this.state = {
          data: {},
          columns: [
            {
              title: messages('common.expense.type')/*费用类型*/,
              width: '20%',
              dataIndex: 'expenseTypeName',
              render: (value) => <Popover content={value} placement="topLeft">{value}</Popover>
            },
            {
              title: messages('expense-1.key1')/*分摊项*/,
              width: '25%',
              dataIndex: 'costCenterItems',
              render: (value) => <Popover content={ this.renderColumns(value, 'costCenterItems')} placement="topLeft">
                { this.renderColumns(value, 'costCenterItems')}
              </Popover>
            },
            {
              title: messages('expense-1.key2')/*申请金额*/,
              width: '15%',
              dataIndex: 'applicationAmount',
              render: (value) => <Popover content={value} placement="topLeft">{value}</Popover>
            },
            {
              title: messages('expense-1.key3')/*剩余未占金额*/,
              width: '20%',
              dataIndex: 'unUsedAmount',
              render: (value) => <Popover content={value} placement="topLeft">{value}</Popover>
            },
            {
              title: messages('expense-1.key4')/*对应申请单*/,
              width:'20%',
              dataIndex: 'businessCodes',
              render: (value) =><Popover content={this.renderColumns(value, 'businessCodes')} placement="topLeft">
                {this.renderColumns(value, 'businessCodes')}
              </Popover>
            },
          ]
        };
      }

      renderColumns = (value, flag) => {
        return value.map(item => {
          return (
            <div>
              {
                flag === 'costCenterItems'
                  ? <div>
                    <span>{item.fieldName || item.costCenterName}：</span>
                    <span>{item.costCenterItemName}</span>
                  </div>
                  : <span>{item}</span>
              }
            </div>
          );
        });
      };

      onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
      };

      componentWillMount() {
        let { data } = this.state;
        if (flag === 'icon') {
          data.title = messages('expense-1.key5')/*申请单分摊*/;
          data.footer = null;
        }

        if (flag === 'button') {
          data.title = messages('expense-1.key6')/*导入申请单分摊*/;
          data.onOk =  this.onOk;
        }
        this.setState({ data });
      }

      onOk = () => {
        const { selectedRowKeys } = this.state;
        this.props.onOk(selectedRowKeys);
      };

      render() {
        const { data, columns, loading, selectedRowKeys } = this.state;
        const rowSelection = {
          selectedRowKeys,
          onChange: this.onSelectChange,
        };
        return (
          <WraooedComponent {...this.props} {...data}>
            <Alert
              message={messages('expense-1.key7')/*关联申请单中有相同费用类型、相同币种、相同分摊项的分摊行或费用行，会合并。*/}
              type="info"
              style={{ marginBottom: '20px' }}
              showIcon
            />
            <Table
              rowKey={'id'}
              columns={columns}
              loading={loading}
              bordered
              dataSource={applicationApportion}
              rowSelection={flag === 'button' ? rowSelection : null}
            />

          </WraooedComponent>
        );
      }
    };
  };

  render() {
    const { flag } = this.props, { visible, loading, buttonLoading } = this.state, MiddleModal = this.WraooedModal(Modal);
    return (
      <section style={{ display: flag === 'icon' ? 'inline-block' : 'block' }}>
        <If value={flag === 'icon'}>
          <Spin spinning={loading}>
            <a
              onClick={() => this.handleLoadingApplicationInvoice()}
              style={{ marginRight: 5 }}>
              <Icon type="link"/>
              {messages('expense-1.key8')/*申*/}
            </a>
          </Spin>
        </If>
        <If value={flag === 'button'}>
          <Spin spinning={buttonLoading}>
            <div className="new-expense-apportion" onClick={() => this.handleShow(true)}>
              <Icon type="plus"/>{messages('expense-1.key6')/*导入申请单分摊*/}
            </div>
          </Spin>
        </If>

        <MiddleModal
          width={800}
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        />
      </section>
    );
  }
}

ApplicationApportion.propTypes = {
  flag: React.PropTypes.string,
  applicationApportionmentId: React.PropTypes.string
};

ApplicationApportion.defaultProps = {
  flag: 'icon'
};


export default ApplicationApportion;
